package com.fulihui.information.core.redis;

import com.fulihui.information.core.db.ContentSortDB;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.Set;

/**
 * @author Willard Hu on 2017/1/11.
 */
public abstract class AbstractRedisContentSortDB implements ContentSortDB {
    @Autowired
    private JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    protected long doSave(String key, String contentId, double score) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zadd(key, score, contentId);
        }
    }

    protected long doBathSave(String key, Map<String, Double> params) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zadd(key, params);
        }
    }

    protected double doIncrScore(String key, String contentId, double num) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zincrby(key, num, contentId);
        }
    }

    protected Set<String> doRange(String key, int start, int end) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrevrange(key, start, end);
        }
    }

    protected Set<String> doRangeByScore(String key, double min, double max) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrangeByScore(key, min, max);
        }
    }

    protected long doRangeByScoreCount(String key, double min, double max) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zcount(key, min, max);
        }
    }

    protected long doSize(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zcard(key);
        }
    }

    protected long doRemove(String key, String... ids) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zrem(key, ids);
        }
    }

    protected long doRemoveRange(String key, int start, int end) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zremrangeByRank(key, start, end);
        }
    }

}
